package com.jsls.netspri.controller.admin;

import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.jsls.netspri.dao.SingleDataDao;
import com.jsls.netspri.dao.UserDao;
import com.jsls.netspri.entity.Page;
import com.jsls.netspri.entity.User;

@Controller
@Transactional
@RequestMapping("/admin")
public class adminController {
	@Resource
	private UserDao userDao;
	
	@Resource
	private SingleDataDao singleDataDao;
	
	//分页显示用户信息列表
	@RequestMapping(value="/list/{currentPage}",method=RequestMethod.GET)
	public String toUserList(@PathVariable(value="currentPage")Integer currentPage, Model model){
		
		/*List<User> users = userDao.findAll();*/
		
		Page page = new Page();
		page.setCurrentPage(currentPage);
		
		
		int totalUser = userDao.findRow();
		int pageSize= page.getPageSize();
		int totalPage =1;
		if(totalUser%pageSize==0){
			totalPage= totalUser/pageSize;
		}else{
			totalPage= totalUser/pageSize + 1;
		}
		
				
		page.setTotalPage(totalPage);;
		
		
		List<User> users= userDao.findPage(page);
		
		model.addAttribute("users", users);
		model.addAttribute("page", page);
		
		
		return "/admin/userlist";
	}
	
	//转到添加用户界面
	@RequestMapping(value="/toadd",method=RequestMethod.GET)
	public String toAddUser(){
		return "/admin/adduser";
	}
	

	//添加用户
	@RequestMapping(method=RequestMethod.POST)
	public String addUser(User addUser){
		
		
		userDao.addUser(addUser);
		
		return "redirect:admin/list/1";
		
	}
	
	//删除用户
	@ResponseBody
	@RequestMapping(value="/{id}",method=RequestMethod.DELETE)
	public boolean deleteUser(@PathVariable(value="id")Integer id){
		
		userDao.deleteUserById(id);
		
		//同时删除用户相关联的监测数据
		singleDataDao.deleteByUserId(id);
		return true;
	}
	
	//登出
	@RequestMapping(value="/logout",method=RequestMethod.GET)
	public String logout(HttpSession session){
		
			session.setMaxInactiveInterval(0);
			session.invalidate();
			
		return "redirect:/login/tologin";
	}
}
